/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package me.everdras.WordFilter;


import java.util.ArrayList;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerListener;
import java.util.LinkedList;
import java.util.Scanner;

/**
 *
 * @author Josh
 */
class WFPlayerListener extends PlayerListener {
    
    private WordFilter parent;
    private ArrayList<FilteredWord> words;
    
    
    public WFPlayerListener(WordFilter parent) {
        
        this.parent = parent;
        words =  parent.getWords();
        
        
    }
    
    @Override
    public void onPlayerChat(PlayerChatEvent event) {
        if(!parent.isFiltering())
            return;
        
        String msg = event.getMessage();
        
        switch(parent.getMethod()) {
            //replaces the entire word if any part of the word matches a filtered String regardless of case
            case REPLACE_ALL:
                Scanner scan = new Scanner(msg);

                String nuMsg = "";
                String cur = null;
                while(scan.hasNext()) {
                    cur = scan.next();
                    for(FilteredWord w : words) {
                        if(cur.toLowerCase().contains(w.getWord().toLowerCase())) {
                            cur = w.getReplacement();
                        }
                    }

                    nuMsg += cur;
                    nuMsg += " ";

                }
                
                msg = nuMsg;
                break;
                
                //replaces the part of the word that matches the filtered string, case sensitive
            case REPLACE_PART:
                for(FilteredWord w : words) {
                    msg = msg.replaceAll(w.getWord(), w.getReplacement());
                }
                break;
                
                //replaces the word with the filtered word if the whole word matches a filtered word
            case REPLACE_WORD:
                scan = new Scanner(msg);
                
                cur = null;
                nuMsg = "";
                
                while(scan.hasNext()) {
                    cur = scan.next();
                    
                    for(FilteredWord w: words) {
                        if(cur.equals(w.getWord())) {
                            cur = w.getReplacement();
                        }
                    }
                    nuMsg += cur;
                    nuMsg += " ";
                }
                msg = nuMsg;
                
                break;
    }
        
        
        //msg.replaceAll("mod", "peoples' champion");
        //msg.replaceAll("Mod", "Peoples' champion");
        //lulz
        
        event.setMessage(msg);
    }
    
    public void setWords(ArrayList<FilteredWord> rep) {
        
        words = rep;
    }
    
    
    
    
}
